﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.Framework.Net;
using ZyGames.Framework.RPC.Sockets;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 发送聊天消息
	/// </summary>
	public class Action10035 : BaseAction
	{
		private int _userId;
		private int _tableId;
		private GameUser _currentGameUser;
		private TableData _currentTable;
		private string _chatMsg;

		public Action10035(HttpGet actionGetter)
			: base((short)ActionType.DZSendChatMsg, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableID",ref  _tableId) &&
				httpGet.GetInt("UserID", ref _userId) &&
				httpGet.GetString("ChatMsg", ref _chatMsg))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			try
			{
				_currentGameUser = GameTable.Current.GetUser(_userId);
				if (_currentGameUser == null)
				{
					ErrorCode = Language.Instance.ErrorCode;
					return false;
				}
				_currentTable = GameRoom.Current.GetTableData(_tableId);
				if (_currentTable == null)
				{
					Tool.WriteErrorLine("消息10035获得房间不存在");
					return false;
				}
				return true;
			}
			catch (Exception ex)
			{
				Tool.WriteErrorLine("10035发送聊天消息异常:" + ex.ToString());
				return false;
			}
		}

		public override void TakeActionAffter(bool state)
		{
			if (_currentTable != null)
			{
				var userList = ClientNotifier.GetUserList(_currentTable);
				var list = new List<IUser>();
				foreach (var user in userList)
				{
					list.Add(new SessionUser(user));
				}
				var parameters = new Parameters();
				parameters["TableID"] = _tableId;
				parameters["UserID"] = _userId;
				parameters["ChatMsg"] = _chatMsg;
				ActionFactory.SendAction(list, (int)ActionType.DZBroadcastChatMsg, parameters, (asyncResult) =>
				{
					Console.WriteLine("广播Action 10036 广播发送聊天消息 send result:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail");
				});
			}
			base.TakeActionAffter(state);
		}
	}
}
